package cn.com.ejiakanghu.service;

import cn.com.ejiakanghu.core.utils.RespUtil;
import cn.com.ejiakanghu.core.vo.BaseResult;
import cn.com.ejiakanghu.dto.AgentNearbySaleJson;
import cn.com.ejiakanghu.dto.GoodsBaseData;
import cn.com.ejiakanghu.dto.PageData;
import cn.com.ejiakanghu.form.NearbySaleUserForm;
import cn.com.ejiakanghu.vo.AgentComboListVo;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import org.linlinjava.litemall.db.dao.AgedmallCustomTemplateMapper;
import org.linlinjava.litemall.db.dao.AgedmallTagsMapper;
import org.linlinjava.litemall.db.dao.app.AppAgentMapper;
import org.linlinjava.litemall.db.dao.app.AppGoodsMapper;
import org.linlinjava.litemall.db.dao.divided.LitemallGoodsAgentMapper;
import org.linlinjava.litemall.db.dao.logistics.LogisticsMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.vo.app.StoreGoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class AgentManager {
    @Autowired
    private AgedmallAgentService agedmallAgentService;
    @Autowired
    private AgedmallAgentComboService agedmallAgentComboService;
    @Autowired
    private LitemallGoodsService goodsService;
    @Autowired
    private GoodsManager goodsManager;
    @Autowired
    private AgedmallAgentGoodsService agedmallAgentGoodsService;
    @Autowired
    private AgedmallStoreGoodsService agedmallStoreGoodsService;
    @Resource
    private AgedmallCustomTemplateMapper agedmallCustomTemplateMapper;
    @Resource
    private AgedmallTagsMapper agedmallTagsMapper;
    @Resource
    private LitemallGoodsAgentMapper litemallGoodsAgentMapper;
     @Resource
    private LitemallGoodsAgentService litemallGoodsAgentService;

    @Resource
    private AppGoodsMapper appGoodsMapper;

    @Resource
    private LogisticsMapper logisticsMapper;

    @Resource
    private AppAgentMapper appAgentMapper;

    public BaseResult addCombo(Integer userId, String goodsIds, String shareName) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        AgedmallAgent agent = agedmallAgentService.getDoctorByUid(userId);
        if (null == agent) {
            return RespUtil.badArgumentValue();
        }
        AgedmallAgentCombo agedmallAgentCombo = new AgedmallAgentCombo();
        agedmallAgentCombo.setAgentId(agent.getId());
        agedmallAgentCombo.setGoodsIds(goodsIds);
        agedmallAgentCombo.setName(shareName);
        agedmallAgentComboService.add(agedmallAgentCombo);
        return RespUtil.success();
    }

    public BaseResult updateComboName(Integer userId, Integer id, String name) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        AgedmallAgentCombo agedmallAgentCombo = agedmallAgentComboService.getById(id);
        if (null == agedmallAgentCombo) {
            return RespUtil.badArgumentValue();
        }
        agedmallAgentCombo.setName(name);
        agedmallAgentComboService.update(agedmallAgentCombo);
        return RespUtil.success();
    }

    public BaseResult updateComboName(Integer userId, String ids) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        List<Integer> idList = Arrays.stream(ids.split(",")).map(p -> Integer.parseInt(p)).collect(Collectors.toList());
        agedmallAgentComboService.deleteBatch(idList);
        return RespUtil.success();
    }

    public BaseResult comboList(Integer userId, String keyword, Integer page, Integer limit) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        AgedmallAgent agent = agedmallAgentService.getDoctorByUid(userId);
        if (null == agent) {
            return RespUtil.badArgumentValue();
        }
        List<AgedmallAgentCombo> comboList = agedmallAgentComboService.comboList(agent.getId(), keyword, page, limit);
        PageInfo<AgedmallAgentCombo> pagedList = PageInfo.of(comboList);

        List<AgentComboListVo> agentComboListVos = comboList.stream()
                .map(p -> {
                    AgentComboListVo agentComboListVo = new AgentComboListVo();
                    agentComboListVo.setId(p.getId()+"");
                    agentComboListVo.setName(p.getName());
                    agentComboListVo.setSaleUserId(agent.getUserId()+"");
                    List<GoodsBaseData> goodsBaseDataList = Arrays.stream(p.getGoodsIds().split(","))
                            .map(q -> {
                                StoreGoodsVo info = agedmallStoreGoodsService.getStoreGoodsById(Integer.parseInt(q));
                                GoodsBaseData goodsBaseData = goodsManager.getGoodsBase(info);
                                return goodsBaseData;
                            }).collect(Collectors.toList());
                    agentComboListVo.setGoodsList(goodsBaseDataList);
                    return agentComboListVo;
                }).collect(Collectors.toList());


        PageData<AgentComboListVo> pageData = new PageData<>();
        pageData.setNowPage(page);
        pageData.setTotalPage(pagedList.getPages());
        pageData.setTotalRows((int) pagedList.getTotal());
        pageData.setRows(agentComboListVos);
        return RespUtil.success(pageData);
    }

    public BaseResult shareComboList(String ids) {
        List<Integer> list = Arrays.stream(ids.split(",")).map(Integer::parseInt).collect(Collectors.toList());
        List<AgedmallAgentCombo> comboList = agedmallAgentComboService.shareComboList(list);
        List<AgentComboListVo> agentComboListVos = comboList.stream()
                .map(p -> {
                    AgedmallAgent agent = agedmallAgentService.getById(p.getAgentId());
                    AgentComboListVo agentComboListVo = new AgentComboListVo();
                    agentComboListVo.setId(p.getId()+"");
                    agentComboListVo.setName(p.getName());
                    agentComboListVo.setSaleUserId(null == agent ? null : agent.getUserId()+"");
                    List<GoodsBaseData> goodsBaseDataList = Arrays.stream(p.getGoodsIds().split(","))
                            .map(q -> {
                                StoreGoodsVo info = agedmallStoreGoodsService.getStoreGoodsById(Integer.parseInt(q));
                                GoodsBaseData goodsBaseData = goodsManager.getGoodsBase(info);
                                return goodsBaseData;
                            }).collect(Collectors.toList());
                    agentComboListVo.setGoodsList(goodsBaseDataList);
                    return agentComboListVo;
                }).collect(Collectors.toList());
        return RespUtil.success(agentComboListVos);
    }

    public BaseResult goodsList(Integer saleUserId, String keyword, Integer page, Integer limit) {
        AgedmallAgent agent = agedmallAgentService.getCommonByUid(saleUserId);
        if (null == agent) {
            return RespUtil.badArgumentValue();
        }
        //根据推广方案id查询方案信息
        AgedmallCustomTemplate customTemplate = agedmallCustomTemplateMapper.selectByPrimaryKey(agent.getPromotionScheme().intValue());
        //获取商品信息
        String goodsId= customTemplate.getCanCustomGoods();
        List<Integer> sgId = null;
        List<LitemallGoods> litemallGoodsList = null;
        //根据方案信息找商品信息
        if(customTemplate.getCanCustomGoodsType() != 0 &&
                    customTemplate.getCanCustomGoodsType() != 1){//不参与商品
                litemallGoodsList = litemallGoodsAgentService.getAgedmallCustomTemplateInfoNotAgent(goodsId,page,limit);
                StringBuffer sb = new StringBuffer();
                for (LitemallGoods lg : litemallGoodsList){
                    sb.append(lg.getId()).append(",");
                }
                String goodsNotId = sb.substring(0,sb.length()-1);
                customTemplate = new AgedmallCustomTemplate();
                customTemplate.setCanCustomGoods(goodsNotId);
                customTemplate.setCanCustomStore(customTemplate.getCanCustomStore());
        }
        sgId = this.getSroreGoodsId(customTemplate,keyword);
        List<GoodsBaseData> baseDataList = this.baseDataList(sgId);
        PageInfo<GoodsBaseData> pagedList = PageInfo.of(baseDataList);
        PageData<GoodsBaseData> pageData = new PageData<>();
        pageData.setNowPage(page);
        pageData.setTotalPage(pagedList.getPages());
        pageData.setTotalRows((int) pagedList.getTotal());
        pageData.setRows(baseDataList);
        return RespUtil.success(pageData);
    }


    private List<GoodsBaseData> baseDataList (List<Integer> sgId){
        List<GoodsBaseData> goodsBaseDataList = new ArrayList<>();
            for(Integer id : sgId){
                StoreGoodsVo info = agedmallStoreGoodsService.getStoreGoodsById(id);
                GoodsBaseData goodsBaseData = goodsManager.getGoodsBase(info);
                goodsBaseDataList.add(goodsBaseData);
            }
        return goodsBaseDataList;
    }

    /**
     * 查询门店和商品关联id
     * @param customTemplate
     * @return
     */
    private List<Integer> getSroreGoodsId(AgedmallCustomTemplate customTemplate,String keyword){
        List<Integer> sgId = litemallGoodsAgentMapper.getSroreGoodsId(customTemplate.getCanCustomGoods(),customTemplate.getCanCustomStore(),keyword);
        return sgId;
    }


    public BaseResult getNearbySaleUserId(NearbySaleUserForm nearbySaleUserForm){
        String type="";
        try {
            type= URLDecoder.decode(nearbySaleUserForm.getType(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            return RespUtil.fail(500,"参数转码失败");
        }

        AgentNearbySaleJson agentNearbySaleJson = JSON.parseObject(type, AgentNearbySaleJson.class);
        List<AgedmallStore> storeList = appGoodsMapper.getNearByStoreIdsByLngAndLat(agentNearbySaleJson.getStoreType(), nearbySaleUserForm.getLng(), nearbySaleUserForm.getLat());
            if(storeList!=null){
                AgedmallAgent agentIdByStoreId = appAgentMapper.getAgentIdByStoreId(storeList.get(0).getId().intValue());
                if(ObjectUtil.isNotNull(agentIdByStoreId)){
                    Map<String,Object> map=new HashMap<>();
                    map.put("saleUserId",agentIdByStoreId.getId());
                    return RespUtil.success(map);
                }
            }

        return RespUtil.success();
    }

}
